package com.knife.interfaces.extension.producer;

import com.knife.interfaces.entity.KnifeInterfaceLogRecord;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

import static com.knife.interfaces.extension.constants.KnifeInterfaceRocketMQConstant.INTERFACE_CONSUMER_TAG;
import static com.knife.interfaces.extension.constants.KnifeInterfaceRocketMQConstant.INTERFACE_TOPIC;

/**
 * @author tianhao.luo@hand-china.com
 * @version 1.0
 * @date 2022年03月09日 星期三 6:48 下午
 * @description
 * @since 1.0
 */
@Component
//@ConditionalOnBean(value = DefaultMQProducer.class) 疑问：为什么加了这个条件之后无法注入了
public class KnifeInterfaceLogMessageProducer {

    public static final Logger LOGGER = LoggerFactory.getLogger(KnifeInterfaceLogMessageProducer.class);

    @Autowired
    private DefaultMQProducer defaultMQProducer;


    public void pushInterfaceLogAfterEndurance(KnifeInterfaceLogRecord knifeInterfaceLogRecord) {
        LOGGER.debug("KnifeInterfaceLogMessageProducer----准备生产日志记录消息");
        if (Objects.nonNull(knifeInterfaceLogRecord)) {
            try {
                if (defaultMQProducer != null) {
                    // 异步发送消息，提示可以记录下本次请求的IP
                    Message message = new Message(INTERFACE_TOPIC,INTERFACE_CONSUMER_TAG, knifeInterfaceLogRecord.getInvokeKey().getBytes(StandardCharsets.UTF_8));
                    // 设置延时等级3,这个消息将在10s后发送(现在只支持固定的几个时间,详见delayTimeLevel)
                    message.setDelayTimeLevel(2);
                    defaultMQProducer.send(message);
                    LOGGER.debug("KnifeInterfaceLogMessageProducer----生产日志记录消息成功");
                } else {
                    LOGGER.debug("RocketMQ未启动注入");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
